package com.mjk.common.core.rmq.conf;

import com.mjk.common.base.constns.BeeCommonConstns;
import com.mjk.common.core.rmq.EventBus;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.DefaultClassMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
/**
 * 
* @author mjk  
* @date 2019年3月11日
 */
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("bee.rmq")
@ConditionalOnProperty(name ="bee.rmq", havingValue ="true")
public class RmqAutoConfiguration extends RmqProperty{
	@PreDestroy
	public void destroy() {
		EventBus.destroy();
	}


	@Bean
	public MessageConverter jsonMessageConverter(){
		DefaultClassMapper mapper = new DefaultClassMapper();
		mapper.setTrustedPackages(BeeCommonConstns.BASE_PACKAGE);
		Jackson2JsonMessageConverter conver = new Jackson2JsonMessageConverter();
		conver.setClassMapper(mapper);
		return conver;
	}

	@Bean
	@ConditionalOnProperty("bee.rmq.host")
	@ConditionalOnMissingBean
	public SubscribeAnnotationBeanFactory subscribeAnnotationBeanFactory2() {
		EventBus.init(this);
		return new SubscribeAnnotationBeanFactory();
	}

	@Bean
	@ConditionalOnBean(SubscribeAnnotationBeanFactory.class)
	public ConnectionFactory rabbitConnection() {
		return EventBus.getChannel().getConnectionFactory();
	}
}
